//
//  AllMovieCommentViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/24.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "AllMovieCommentViewController.h"
#import "MovieCommentTableViewCell.h"
#import "CommitStarsView.h"
static NSString *cellIdentify = @"MovieCommentTableViewCell";

@interface AllMovieCommentViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;
@property (strong, nonatomic) IBOutlet UILabel *commentNumber;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation AllMovieCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    // Do any additional setup after loading the view.
    _pageNO =  1;
    _heightArray = [NSMutableArray array];
    _commitArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    //注册
     [self.tableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];

    
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求评论数据
            [self getComments];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.commitArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求评论数据
            [self getComments];
        });
    }
    
}
#pragma mark -- 请求评论数据
- (void)getComments{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_type == 2) {//团购评论列表
        [dic setObject:_commentId forKey:@"mgpdId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppMallGrouponComment withHttpType:@"POST" withTag:SX_SX_queryAppMallGrouponComment];
    }else if (_type == 3){//团购店铺评论
        [dic setObject:_commentId forKey:@"storeId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppMallGrouponCommentByStoreId withHttpType:@"POST" withTag:SX_SX_queryAppMallGrouponCommentByStoreId];
    
    }
    
    

}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MovieCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify ];
    if (cell== nil) {
        cell = [[MovieCommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
  
    
        NSDictionary * dic = _commitArray[indexPath.row];
        NSString * image = dic[@"memberImg"];
        if (image) {
                [cell.headImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
                cell.headImage.image = [UIImage imageNamed:@"comment1"];
        }
    
    double star = [[NSString stringWithFormat:@"@%.1f",[dic[@"mgcoCommentStars"]floatValue ]]doubleValue];
    
    CommitStarsView * stars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(13, 50, 80, 15), NO) Stars:star];
    [cell addSubview:stars];

    cell.commentInfo.frame = flexibleFrame(CGRectMake(10, 72, 300, 15), YES);
    cell.commentInfo.numberOfLines = 0;
    cell.commentInfo.text = dic[@"mgcoContent"];
    [cell.commentInfo sizeToFit];
    
    cell.name.text = dic[@"mgcoAuthor"];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[dic[@"commentDate"] integerValue]/1000];
    cell.date.text = [formatter stringFromDate:confromTimesp];
    
    
        return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commitArray.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
    return height ;
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    
    if (tag == SX_SX_queryAppMallGrouponComment ||tag == SX_SX_queryAppMallGrouponCommentByStoreId){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
//            _totle = [database[@"result"][@"totalResults"] integerValue];
            if (_totle > PageSize) {
                __weak __typeof(self) weakSelf = self;
                if (!self.tableView.footer) {
                    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [weakSelf loadMoreData];
                    }];
                }
            }
            if (self.pageNO == 1) {
                [self.commitArray removeAllObjects];
            }
            NSArray *arr = database[@"result"];
            if (_type == 3) {
                arr = database[@"result"][@"comment"];
            }
            for (id entity in arr) {
                [self.commitArray addObject:entity];
            }
                for (int i = 0; i<_commitArray.count; i++) {
                    NSString * commentImage = _commitArray[i][@"mgciImag"];
                    NSString * comment = _commitArray[i][@"mgcoContent"];
                    NSInteger height = 0;
                    if (commentImage.length==0 ) {
                        height = 90;
                    }else{
                        height = 130;
                    }
                        
                    
                    int lines = 0;
                    CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                    lines = cSize.width/300*VerticalRatio() + 1 ;
                    
                    height  += lines * 17;
                    
                    [_heightArray addObject:@(height)];
                }
            NSString * coment = @"评论";
            if (_type == 3 || _type == 1) {
                coment = @"全部评价";
            }
            _commentNumber.text = [NSString stringWithFormat:@"%@(%ld)",coment,_commitArray.count];
            
            _tableView.delegate = self;
            _tableView.dataSource = self;
            [_tableView reloadData];
     
        }
        
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
